
import { DatePicker, Dropdown, Select, Switch } from "antd";
import React, { useEffect, useState } from "react";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import { $AddZero, $eventBus } from "../../../../common/utils";
import 'dayjs/locale/zh-cn';
import dayjs from 'dayjs';
import plusImage from "../../../../assets/image/icon_plus_square@2x.png";
import minusImage from "../../../../assets/image/icon_minus_square@2x.png";
import lessModule from "./index.module.less";
import { MenuProps } from "rc-menu";
import { $Http } from "../../../../network";

// 变电站能耗页面-头部菜单tab组件
const SubstationEnergyConsumptionPage_HeaderMenuTabComponent: React.FC = () => {
    const navigate = useNavigate();
    const tabList = [{ name: "实时功率", routerName: "realTimePower" }, { name: "能耗统计", routerName: "energyConsumptionStatistics" }]
    const [tabName, setTabName] = useState<string>(tabList[0].name)
    const locationData = useLocation()

    const init_tabName = () => {
        setTabName(tabList.find((item) => !locationData.pathname.split("/")[3] || item.routerName === locationData.pathname.split("/")[3])?.name ?? "")
        setTimeout(() => {
            $eventBus.emit("eventBus_homePageSubstationEnergyConsumptionPageTabName", tabList.find((item) => !locationData.pathname.split("/")[3] || item.routerName === locationData.pathname.split("/")[3])?.name ?? "")
        });
    }

    const click_tab = (tabData: object) => {
        setTabName(tabData["name"])
        navigate(`/home/substationEnergyConsumption/${tabData["routerName"]}`)
        $eventBus.emit("eventBus_homePageSubstationEnergyConsumptionPageTabName", tabData["name"])
    }

    useEffect(() => {
        init_tabName()
    }, [])

    return (
        <div className={`${lessModule["homePageSubstationEnergyConsumptionPage-headerMenu__substationEnergyConsumptionPageHeaderMenuTabComponent"]}`}>
            {
                tabList.map((item, idx) => {
                    return (
                        <div className={`${lessModule["headerMenu-substationEnergyConsumptionPageHeaderMenuTabComponent__tabItem"]}`}
                            style={{
                                color: tabName === item.name ? "#FFFFFF" : "#B8D6E6",
                                backgroundColor: tabName === item.name ? "rgba(23,161,230,0.5)" : "rgba(23,161,230,0.1)",
                                borderColor: tabName === item.name ? "#17A1E6" : "rgba(23,161,230,0.3)",
                                borderWidth: tabName === item.name ? "0 0 1px 0" : "1px"
                            }}
                            key={'tabList' + idx}
                            onClick={() => click_tab(item)}>{item.name}</div>
                    )
                })
            }
        </div>
    )
}

// 变电站能耗页面-头部筛选组件
const SubstationEnergyConsumptionPage_HeaderMenuFilterComponent: React.FC = () => {
    let [scaleValue, setScaleValue] = useState<number>(1)
    let [isSwitch, setIsSwitch] = useState<boolean>(true)
    const items: MenuProps['items'] = [
        {
            key: "1",
            label: (<div className={lessModule["scale__dropdown__items"]} onClick={() => change_scale(4)}>400%</div>)
        },
        {
            key: "2",
            label: (<div className={lessModule["scale__dropdown__items"]} onClick={() => change_scale(2)}>200%</div>)
        },
        {
            key: "3",
            label: (<div className={lessModule["scale__dropdown__items"]} onClick={() => change_scale(1.5)}>150%</div>)
        },
        {
            key: "4",
            label: (<div className={lessModule["scale__dropdown__items"]} onClick={() => change_scale(1)}>100%</div>)
        },
        {
            key: "5",
            label: (<div className={lessModule["scale__dropdown__items"]} onClick={() => change_scale(0.5)}>50%</div>)
        },
        {
            key: "6",
            label: (<div className={lessModule["scale__dropdown__items"]} onClick={() => change_scale(0.25)}>25%</div>)
        }
    ]
    const locationData = useLocation()
    let dataTypeList = [{ label: "总能耗与变压器损耗" }, { label: "母线能耗" }, { label: "馈线能耗" }]
    let [dataTypeName, setDataTypeName] = useState<string>(dataTypeList[0].label)
    let dateTypeList = [{ label: "日" }, { label: "月" }, { label: "年" }]
    let [dateTypeName, setDateTypeName] = useState<any>(dateTypeList[0]["label"])
    let [dateValue, setDateValue] = useState<dayjs.Dayjs>(dayjs())
    let [siteName, setSiteName] = useState<string>(`${JSON.parse(sessionStorage.homePage_freewayList)[0].label}/${JSON.parse(sessionStorage.homePage_freewayList)[0].options[0].label}`)
    let [tabName, setTabName] = useState<string>("实时功率")
    let [sourceData, setSourceData] = useState<object>({})
    const change_switch = (checked: boolean) => {
        isSwitch = checked
        setIsSwitch(isSwitch)
        $eventBus.emit("eventBus_homePageSubstationEnergyConsumptionPageData", { isSwitch, scaleValue })
    }
    const click_scale = (type: string) => {
        type === "minus" ? scaleValue -= 0.1 : type === "plus" && (scaleValue += 0.1)
        setScaleValue(scaleValue)
        $eventBus.emit("eventBus_homePageSubstationEnergyConsumptionPageData", { isSwitch, scaleValue })
    }
    const change_scale = (value: number) => {
        scaleValue = value
        setScaleValue(scaleValue)
        $eventBus.emit("eventBus_homePageSubstationEnergyConsumptionPageData", { isSwitch, scaleValue })
    }
    const change_dataTypeName = (value: string) => {
        dataTypeName = value
        setDataTypeName(dataTypeName)
        $eventBus.emit("eventBus_homePageSubstationEnergyConsumptionPageenergyConsumptionStatisticsData", { ...sourceData, dataTypeName })
    }
    const change_dateTypeName = (value: string) => {
        dateTypeName = value
        setDateTypeName(dateTypeName)
        dateValue = dayjs()
        setDateValue(dateValue)
        http_eneryConsumeGetDateEnery()
    }
    const change_dateValue = (value: any) => {
        dateValue = value
        setDateValue(dateValue)
        http_eneryConsumeGetDateEnery()
    }
    const change_siteName = (value: string) => {
        siteName = value
        setSiteName(siteName)
        http_eneryConsumeGetDateEnery()
    }

    const disabled_date = (current: dayjs.Dayjs) => {
        return current && current > dayjs().endOf("day");
    };

    const eventBus_on = () => {
        // 变电站能耗tab名称
        $eventBus.addListener("eventBus_homePageSubstationEnergyConsumptionPageTabName", (res) => {
            tabName = res
            setTabName(res)
            if (tabName === "能耗统计") {
                http_eneryConsumeGetDateEnery()
            }
        })
    }
    const eventBus_off = () => {
        // 变电站能耗tab名称
        $eventBus.removeAllListeners("eventBus_homePageSubstationEnergyConsumptionPageTabName")
    }
    const http_eneryConsumeGetDateEnery = () => {
        const paramsData = {
            date_type: dateTypeName,
            substation_name: siteName,
            data_time: dateValue.format(dateTypeName === "年" ? "YYYY" : dateTypeName === "月" ? "YYYY-MM" : "YYYY-MM-DD")
        }
        $Http("eneryConsumeGetDateEnery", paramsData, "post").then((res) => {
            sourceData = res
            setSourceData({ ...sourceData })
            $eventBus.emit("eventBus_homePageSubstationEnergyConsumptionPageenergyConsumptionStatisticsData", { ...sourceData, dataTypeName })

        })
    }
    useEffect(() => {
        eventBus_on()
        return () => {
            eventBus_off()
        }
    }, [])
    useEffect(() => {
        dataTypeName = dataTypeList[0]["label"]
        setDataTypeName(dataTypeName)
    }, [locationData.pathname])

    return (
        <div className={`${lessModule["homePageSubstationEnergyConsumptionPage-headerMenu__homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent"]}`}>
            {
                tabName === "实时功率" && <>
                    <Switch className={`${lessModule["headerMenu-homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent__switch"]}`} style={{ opacity: isSwitch ? 1 : 0.5 }} checkedChildren="指标显示" unCheckedChildren="指标隐藏" defaultChecked onChange={change_switch} />
                    <div className={`${lessModule["headerMenu-homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent__scale"]}`}>
                        <img className={`${lessModule["homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent-scale__image"]}`} src={minusImage} onClick={() => click_scale("minus")} />
                        <Dropdown overlayClassName={lessModule["homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent-scale__dropdown"]} menu={{ items }} trigger={['click']} placement="bottom">
                            <span className={`${lessModule["homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent-scale__value"]}`}>{Math.floor(scaleValue * 100)}%</span>
                        </Dropdown>
                        <img className={`${lessModule["homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent-scale__image"]}`} src={plusImage} onClick={() => click_scale("plus")} />
                    </div>
                </>
            }
            {

                tabName === "能耗统计" && <>
                    <span>数据类型：</span>
                    <Select
                        popupClassName="homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent-dataTypeSelect__selectDropdown"
                        className={`${lessModule["headerMenu-homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent__dataTypeSelect"]}`}
                        value={dataTypeName}
                        onChange={change_dataTypeName}
                        options={dataTypeList}
                        fieldNames={{ value: "label" }}
                    />
                    <span>时间：</span>
                    <Select
                        popupClassName="homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent-dateTypeSelect__selectDropdown"
                        className={`${lessModule["headerMenu-homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent__dateTypeSelect"]}`}
                        value={dateTypeName}
                        onChange={change_dateTypeName}
                        options={dateTypeList}
                        fieldNames={{ value: "label" }}
                    />
                    <DatePicker popupClassName="homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent-datePicker__pickerDropdown" className={`${lessModule["headerMenu-homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent__datePicker"]}`} value={dateValue} picker={dateTypeName == "年" ? "year" : dateTypeName == "月" ? "month" : "date"} allowClear={false} disabledDate={disabled_date} onChange={change_dateValue} />
                    <div className={`${lessModule["headerMenu-homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent__division"]}`}></div>

                    <div className={`${lessModule["headerMenu-homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent__siteBox"]}`}>
                        <Select
                            className={`${lessModule["homePageSubstationEnergyConsumptionPageHeaderMenuFilterComponent-siteBox__siteSelect"]}`}
                            popupClassName="siteBox-siteSelect__selectDropdown"
                            value={siteName}
                            optionLabelProp="labelProp"
                            onChange={change_siteName}
                            options={JSON.parse(sessionStorage.homePage_freewayList)}
                            fieldNames={{ value: "labelProp" }}
                        />
                    </div>
                </>
            }
        </div>

    )
}





// 主页-变电站能耗页面
const HomePage_SubstationEnergyConsumptionPage: React.FC = () => {
    const locationData = useLocation()
    return (
        <div className={`${lessModule["homePageSubstationEnergyConsumptionPage"]}`} style={{ border: locationData.pathname.split("/")[3] === "realTimePower" ? "1px solid rgba(23, 161, 230, 0.3)" : 'none' }}>
            <header className={`${lessModule["homePageSubstationEnergyConsumptionPage-headerMenu"]}`}>
                <SubstationEnergyConsumptionPage_HeaderMenuTabComponent />
                <SubstationEnergyConsumptionPage_HeaderMenuFilterComponent />
            </header>
            <main className={`${lessModule["homePageSubstationEnergyConsumptionPage-main"]}`}>
                <Outlet />
            </main>
        </div>
    )
}

export default HomePage_SubstationEnergyConsumptionPage